import React from "react";
import store from './redux/store'
import { connect } from 'react-redux';
import { userNameAction, unreadCountActionThunk } from './redux/action'


class ProfileSetting extends React.Component {
    constructor() {
        super();
        this.state = {
            username: '',
            loading: false
        }
    }

    render() {
        return (
            <div className='profile-setting'>
                个人信息设置页面：<br />
                <span style={{ marginRight: '10px' }}>{this.props.username}</span>


                <input placeholder="新用户名"
                    value={this.state.username}
                    onChange={e => this.setState({ username: e.target.value })}
                />
                <button onClick={e => {
                    this.props.changeUserName(this.state.username);
                    this.setState({ username: '' });
                    alert('修改成功');
                }}>修改</button>

                <br />
                由后端耗时2s获取未读消息条数：
                <button onClick={() => {
                    this.setState({ loading: true })
                    // setTimeout(() => {
                    //     const unReadCount = Math.floor(Math.random() * 20);
                    //     this.props.setUnReadCount(unReadCount);
                    //     this.setState({ loading: false })
                    // }, 2000);
                    this.props.setUnReadCount(() => this.setState({ loading: false }));
                }}

                >{this.state.loading ? 'loading...' : '延时获取'}</button>

            </div>
        )
    }
}

export default function CounterConnector() {
    const Connector = connect(
        // mapStateToProps
        state => ({
            username: state.username,
        }),
        // mapDispatchToProps
        // dispatch => ({
        //     changeUserName: (username) => dispatch(userNameAction(username)),
        //     setUnReadCount: (setLoadingFunc) => dispatch(unreadCountActionThunk(setLoadingFunc))
        // })
        // mapDispatchToProps 简化版本: propsDistach: action映射
        {
            changeUserName: userNameAction,
            setUnReadCount: unreadCountActionThunk
        }
    )
        (ProfileSetting)

    return <Connector store={store} />
}